Put the ipynb file and html file in the github branch you created in the last assignment and submit the link to the commit in brightspace
from plotly.offline import init_notebook_mode
import plotly.io as pio
import plotly.express as px
init_notebook_mode(connected=True)
pio.renderers.default = "plotly_mimetype+notebook"
#load data
df = px.data.gapminder()
df.head()
| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 0 | Afghanistan | Asia | 1952 | 28.801 | 8425333 | 779.445314 | AFG | 4 |
| 1 | Afghanistan | Asia | 1957 | 30.332 | 9240934 | 820.853030 | AFG | 4 |
| 2 | Afghanistan | Asia | 1962 | 31.997 | 10267083 | 853.100710 | AFG | 4 |
| 3 | Afghanistan | Asia | 1967 | 34.020 | 11537966 | 836.197138 | AFG | 4 |
| 4 | Afghanistan | Asia | 1972 | 36.088 | 13079460 | 739.981106 | AFG | 4 |
Recreate the barplot below that shows the population of different continents for the year 2007.
Hints:
# Filter the DataFrame to select data for the year 2007
df = px.data.gapminder()
df_2007 = df[df['year']==2007]
# Group the filtered data by continent and calculate the sum of numeric columns
df_2007_new = df_2007.groupby('continent') .agg({'pop': 'sum'}).reset_index()
# Create a bar chart using Plotly Express
df_2007_new_sorted = df_2007_new.sort_values(by='pop', ascending=False)
def format_population(pop):
if pop < 1e9:
return f'{pop/1e6:.0f}M'
else:
return f'{pop/1e9:.1f}B'
df_2007_new_sorted['pop_text'] = df_2007_new_sorted['pop'].apply(format_population)
fig = px.bar(df_2007_new_sorted, x='pop', y='continent', color='continent',
color_discrete_map={'Asia': 'blue', 'Africa': 'green', 'Europe': 'red', 'North America': 'purple', 'South America': 'orange', 'Oceania': 'brown'},
labels={'continent': 'Continent', 'pop': 'Population'},
text='pop_text')
# Customize the layout of the chart: hide the legend
fig.update_layout(showlegend=False)
# Update the layout for the y-axis to order categories by total population in ascending order
fig.update_xaxes(categoryorder='total ascending')
# Customize the text labels on the bars: format with two decimal places and position them outside the bars
fig.update_traces(textposition='outside')
# Display the resulting chart
fig.show()
# Below are the parts of the code in question 1 that decide the order of the continents:
# df_2007_new_sorted = df_2007_new.sort_values(by='pop', ascending=False)
# fig.update_xaxes(categoryorder='total ascending')
Add text to each bar that represents the population
# Below are the parts of the code in question 1 that create the text on each bar:
# fig = px.bar(df_2007_new_sorted, x='pop', y='continent', color='continent',
# color_discrete_map={'Asia': 'blue', 'Africa': 'green', 'Europe': 'red', 'North America': 'purple', 'South America': 'orange', 'Oceania': 'brown'},
# labels={'continent': 'Continent', 'pop': 'Population'},
# text='pop_text')
# fig.update_traces(textposition='outside')
Thus far we looked at data from one year (2007). Lets create an animation to see the population growth of the continents through the years
# Load the Gapminder dataset
df = px.data.gapminder()
# Create a bar chart animation using Plotly Express
fig = px.bar(
df,
x="pop",
y="continent",
color="continent",
animation_frame="year", # Use 'year' as the animation frame
color_discrete_map={
'Asia': 'blue',
'Africa': 'green',
'Europe': 'red',
'North America': 'purple',
'South America': 'orange',
'Oceania': 'brown',
},
labels={'continent': 'Continent', 'pop': 'Population'},
title='Population Growth by Continent Over Time'
)
# Remove the vertical grid lines
fig.update_traces(selector=dict(type='bar'), marker=dict(line=dict(width=0)))
# Customize the layout of the chart
fig.update_layout(showlegend=False)
fig.update_xaxes(categoryorder='total ascending')
# Display the animated chart
fig.show()
Instead of the continents, lets look at individual countries. Create an animation that shows the population growth of the countries through the years
# Load the Gapminder dataset
df = px.data.gapminder()
# Create a bar chart animation using Plotly Express
fig = px.bar(
df,
x="pop",
y="country", # Use 'country' instead of 'continent'
color="country", # Color by country
animation_frame="year", # Use 'year' as the animation frame
labels={'country': 'Country', 'pop': 'Population'},
title='Population Growth by Country Over Time'
)
# Customize the layout of the chart
fig.update_layout(showlegend=False)
fig.update_xaxes(categoryorder='total ascending')
# Display the animated chart
fig.show()
Clean up the country animation. Set the height size of the figure to 1000 to have a better view of the animation
# Load the Gapminder dataset
df = px.data.gapminder()
# Create a bar chart animation using Plotly Express
fig = px.bar(
df,
x="pop",
y="country", # Use 'country' instead of 'continent'
color="country", # Color by country
animation_frame="year", # Use 'year' as the animation frame
labels={'country': 'Country', 'pop': 'Population'},
title='Population Growth by Country Over Time'
)
# Customize the layout of the chart
fig.update_layout(
showlegend=False,
height=1000, # Set the height of the figure to 1000
)
# Display the animated chart
fig.show()
# Load the Gapminder dataset
df = px.data.gapminder()
# Get the top 10 countries by population for the initial frame (year 1952)
top_10_countries = df[df['year'] == 1952].nlargest(10, 'pop')['country']
# Create a filtered DataFrame containing only the top 10 countries
df_filtered = df[df['country'].isin(top_10_countries)]
# Create a bar chart animation using Plotly Express
fig = px.bar(
df_filtered, # Use the filtered DataFrame with only the top 10 countries
x="pop",
y="country", # Use 'country' instead of 'continent'
color="country", # Color by country
animation_frame="year", # Use 'year' as the animation frame
labels={'country': 'Country', 'pop': 'Population'},
title='Top 10 Population Growth by Country Over Time'
)
# Customize the layout of the chart
fig.update_layout(
showlegend=False,
height=1000, # Set the height of the figure to 1000
)
# Set x-axis limits to show the entire range of population values
fig.update_xaxes(range=[0, df['pop'].max()])
fig.update_yaxes(categoryorder='total ascending')
# Display the animated chart
fig.show()